package cn.crm.system.service.impl;

import cn.crm.common.annotation.DataScope;

import cn.crm.common.exception.ServiceException;
import cn.crm.common.utils.SecurityUtils;
import cn.crm.common.utils.StringUtils;
import cn.crm.common.utils.bean.BeanValidators;
import cn.crm.system.domain.pojo.dto.BusinessDto;
import cn.crm.system.domain.pojo.dto.ContactsDto;
import cn.crm.system.domain.pojo.entity.BusinessAndContactsUpdate;
import cn.crm.system.domain.pojo.vo.BusinessVo;
import cn.crm.system.domain.pojo.vo.CaseVo;
import cn.crm.system.domain.pojo.vo.ContactsVo;
import cn.crm.system.mapper.BusinessMapper;
import cn.crm.system.mapper.CaseMapper;
import cn.crm.system.mapper.ContactsMapper;
import cn.crm.system.mapper.SysUserMapper;
import cn.crm.system.service.IBusinessService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.crm.system.domain.pojo.entity.Business;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.crm.common.core.domain.AjaxResult.error;


/**
 * 处理客户的接口
 */

@Slf4j
@Service
public class BusinessServiceImpl implements IBusinessService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private ContactsMapper contactsMapper;
    @Autowired
    private CaseMapper caseMapper;
    @Autowired
    protected Validator validator;
    @Autowired(required = false)
    private SysUserMapper sysUserMapper;

    /**
     * 新增客户的接口
     * @param businessdto
     */
    @Override
    public int insertbusiness(BusinessDto businessdto) {
        log.debug("开始插入客户和联系人业务");
        Business business = new Business();
        //处理传过来来的县市数据
// 使用 Stream API 将列表中的元素转换为字符串并用 '-' 连接
        String  countiesCities =  businessdto.getCountiesCities().stream()
                .map(Object::toString) // 转换为 String
                .collect(Collectors.joining("-")); // 用 '-' 连接

        business.setCountiesCities(countiesCities);
        //        获取到当前用户
        String createAccount = SecurityUtils.getUsername();
        //赋值给业务表里
        business.setCreateUser(createAccount);
        BeanUtils.copyProperties( businessdto,business);
        int businessinsert = businessMapper.Businessinsert(business);
        log.debug("插入客户成功，开始插入联系人");
        //获取到插入客户的id
        Long businessId = business.getId();
        List<ContactsDto> contactse = businessdto.getContactse();
        //将公司的id 以及创建者重新装一个list里存到数据库
        List<ContactsDto> updatedContactse = contactse.stream()
                .peek(contact -> {
                    contact.setBusinessId(businessId);
                    contact.setCreateAccount(createAccount);
                    if (contactse.indexOf(contact) == 0) {
                        contact.setFirst(1L);
                    }
                })
                .collect(Collectors.toList());
        int i = contactsMapper.insertContacts(updatedContactse);
        if(i<1){
            businessinsert=0;
        }
        return  businessinsert;
    }
    //查询公司列表
    @Override
    @DataScope(deptAlias = "d")
    public List<BusinessVo> selectbusinessList(BusinessDto businessdto) {
        List<BusinessVo> businessVos = businessMapper.BusinessSelectList(businessdto);
        return businessVos;
    }
//修改公司列表
    @Override
    public int updatebusiness(BusinessDto businessdto) {
        log.debug("开始修改客户信息");
        Business business = new Business();
        String  countiesCities =  businessdto.getCountiesCities().stream()
                .map(Object::toString) // 转换为 String
                .collect(Collectors.joining("-")); // 用 '-' 连接

        business.setCountiesCities(countiesCities);

        BeanUtils.copyProperties(businessdto,business);
        int businessupdate = businessMapper.Businessupdate(business);
        //然后在判定联系人是否修改，修改的是联系人1的值
        Long businessId = businessdto.getId();
        List<ContactsDto> contactse = businessdto.getContactse();
        ContactsDto firstContact =new ContactsDto();
        int updateCount = 0;
        int insertCount = 0;
        if (contactse != null && !contactse.isEmpty()  ) {


            if (contactse.size() == 1) {
                // 当列表中只有一个元素时，执行修改操作
                 firstContact = contactse.get(0);
                 firstContact.setBusinessId(businessId);
                updateCount = contactsMapper.updateContacts(firstContact);
                System.out.println("修改了 " + updateCount + " 条记录");
            } else {
                // 当列表中有多个元素时，第一个元素执行修改操作，其余元素执行插入操作
                 firstContact = contactse.get(0);
                updateCount = contactsMapper.updateContacts(firstContact);
                contactse.remove(0);
                String createAccount = SecurityUtils.getUsername();
                List<ContactsDto> updatedContactse = contactse.stream()
                        .peek(contact -> {
                            contact.setBusinessId(businessId);
                            contact.setCreateAccount(createAccount);
                        })
                        .collect(Collectors.toList());
                insertCount = contactsMapper.insertContacts(updatedContactse);
            }
        } else {
            System.out.println("联系人列表为空");
        }

            if (updateCount + insertCount == 0){
                businessupdate=0;
            }
        return businessupdate;
    }

    //通过id删除客户资料
    @Override
    public int deletebusiness(Long[] id) {
        int i = businessMapper.Businessdelete(id);
        //然后在通过客户id删联系人

        int contactsRow = contactsMapper.deleteContacts(id);
        return i+contactsRow;
    }
//通过id查询出公司和联系人
    @Override
    public BusinessVo selectbusinessbyid(Long id) {
        log.debug("开始通过id查询出公司的联系人的业务");
        BusinessVo businessvo = businessMapper.SelectBusinessById(id);
        return businessvo;
    }
//查询出所有的公司，以及公司对应的联系人和案件
    @Override
    public List<BusinessVo> selectbusinessListAndcast() {
        // 1. 查询所有公司
        List<BusinessVo> businessVos = businessMapper.selectBusinessAll();
        if (businessVos.isEmpty()) {
            return businessVos;
        }

        // 2. 获取所有公司ID
        List<Long> businessIds = businessVos.stream()
                .map(BusinessVo::getId)
                .collect(Collectors.toList());

        // 3. 批量查询联系人和案件
        List<ContactsVo> allContacts = contactsMapper.batchSelectContactsByBusinessIds(businessIds);
        List<CaseVo> allCases = caseMapper.batchSelectCasesByBusinessIds(businessIds);

        // 4. 使用Map优化数据组装
        Map<Long, List<ContactsVo>> contactsMap = allContacts.stream()
                .collect(Collectors.groupingBy(ContactsVo::getBusinessId));
        Map<Long, List<CaseVo>> casesMap = allCases.stream()
                .collect(Collectors.groupingBy(CaseVo::getBusinessId));

        // 5. 组装数据
        businessVos.forEach(business -> {
            business.setContactsVos(contactsMap.getOrDefault(business.getId(), new ArrayList<>()));
            business.setCaseVos(casesMap.getOrDefault(business.getId(), new ArrayList<>()));
        });

        return businessVos;
    }

    @Override
    public String importBusinessAndcontactsAndcase(List<BusinessAndContactsUpdate> specificationList, boolean updateSupport, String operName) {


            if (StringUtils.isNull(specificationList) || specificationList.isEmpty()) {
                throw new ServiceException("导入参数数据不能为空！");
            }

            int successNum = 0;
            int failureNum = 0;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();

            for (BusinessAndContactsUpdate businessAndContactsUpdate : specificationList) {
                try {
                    // 解析并创建 Business 对象
                    BeanValidators.validateWithException(validator, businessAndContactsUpdate);
                    Business business = new Business();
                    business.setId(businessAndContactsUpdate.getId());
                    business.setCustomerName(businessAndContactsUpdate.getCustomerName());
                    business.setCountiesCities(businessAndContactsUpdate.getCountiesCities());
                    business.setAbbreviation(businessAndContactsUpdate.getAbbreviation());
                    business.setCustomeraddress(businessAndContactsUpdate.getCustomeraddress());
                    business.setCountomtype(businessAndContactsUpdate.getCountomtype());
                    business.setCountomsource(businessAndContactsUpdate.getCountomsource());
                    business.setScale(businessAndContactsUpdate.getScale());
                    business.setCreateUser(operName);
                    String account =operName;
                    //通过operName去查询昵称 在用户表
                    String nickeName = sysUserMapper.selectNickNameByAccount(account);
                    business.setNickName(nickeName);

                    // 检查 Business 是否已存在
                    BusinessVo existingBusiness = businessMapper.selectBusiness(business);
                    if (existingBusiness == null) {
                        // 插入新的 Business 记录

                        businessMapper.Businessinsert(business);
                    } else if (updateSupport) {
                        // 更新现有的 Business 记录
                        BeanValidators.validateWithException(validator, businessAndContactsUpdate);
                         businessMapper.Businessupdate(business);
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、客户名称 " + business.getCustomerName() + " 已存在");
                        continue;
                    }
                    if (existingBusiness == null) {
                        // 解析并创建 Contacts 对象
                        ContactsDto contact = new ContactsDto();
                        contact.setBusinessId(business.getId()); // 假设 Contacts 表中有一个外键关联 Business 表
                        contact.setName(businessAndContactsUpdate.getName());
                        contact.setContactNumber(businessAndContactsUpdate.getContactNumber());
                        contact.setFirst(1L);
                        contact.setCreateAccount(operName);
                        List<ContactsDto> insertContactse = new ArrayList<>();
                        insertContactse.add(contact);

                        BeanValidators.validateWithException(validator, contact);
                        // 插入新的 Contacts 记录
                        contact.setCreateBy(SecurityUtils.getUsername());
                        contactsMapper.insertContacts(insertContactse);
                    }else {
                        //否则更新联系人
                        ContactsDto contactsDto = new ContactsDto();
                        contactsDto.setBusinessId(existingBusiness.getId());
                        contactsDto.setName(businessAndContactsUpdate.getName());
                        contactsDto.setContactNumber(businessAndContactsUpdate.getContactNumber());
                        contactsDto.setCreateAccount(operName);
                        BeanValidators.validateWithException(validator, contactsDto);
                        contactsMapper.updateContactsOne(contactsDto);
                    }

                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户名称 " + business.getCustomerName() + " 及联系人信息导入成功");
                } catch (Exception e) {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、客户名称 " + businessAndContactsUpdate.getCustomerName() + " 导入失败：";
                    failureMsg.append(msg + e.getMessage());
                    log.error(msg, e);
                }
            }

            if (failureNum > 0) {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            } else {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            }

            return successMsg.toString();

    }
    //查询客户总数
    @Override
    public Long selectcount() {
        Long selectcount = businessMapper.selectcount();
        return selectcount;
    }
    //查询百分比
    @Override
    public Long selectpercentage() {
        Long selectpercentage = businessMapper.selectpercentage();
        return selectpercentage;
    }

    @Override
    public List<BusinessVo> selectbusinessListTaiwan() {
        List<BusinessVo> businessVo = businessMapper.selectbusinessListTaiwan();
        return businessVo;
    }


}

